package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.ArticleMapper;
import com.example.forum.dao.ArticleReplyMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.model.ArticleReply;
import com.example.forum.services.IArticleReplyService;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IUserService;
import com.example.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ArticleReplyServiceImpl implements IArticleReplyService {

    @Autowired
    private ArticleReplyMapper articleReplyMapper;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private IArticleService articleService;
    
    @Autowired
    private IUserService userService;

    @Override
    public void create(ArticleReply articleReply) {
        //校验参数
        if(articleReply==null||articleReply.getArticleId()==null|| StringUtil.isEmpty(articleReply.getContent())){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询帖子信息
        Article article = articleMapper.selectByPrimaryKey(articleReply.getArticleId());
        //校验帖子状态
        if(article==null||article.getDeleteState()==1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if(article.getState()==1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //填充参数
        articleReply.setState((byte) 0);
        articleReply.setLikeCount(0);
        articleReply.setDeleteState((byte) 0);
        Date date=new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);
        //写入数据
        int row = articleReplyMapper.insertSelective(articleReply);
        if(row!=1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新帖子回复数量
        articleService.addOneReplyCountById(articleReply.getArticleId());
        //更新用户评论数量
        userService.addOneCommentCountById(articleReply.getPostUserId());
        log.info("新增帖子回复成功 Article id="+articleReply.getArticleId()+"user id="+articleReply.getPostUserId());
    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        //校验参数
        if(articleId==null||articleId<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询帖子 校验帖子状态
        Article article = articleService.selectById(articleId);
        if(article==null||article.getDeleteState()==1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if(article.getState()==1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //校验通过 查询该文章的所有回复表
        List<ArticleReply> articleReplies = articleReplyMapper.selectByArticleIdWithUser(articleId);
        if(articleReplies==null){
            articleReplies=new ArrayList<>();
        }
        return articleReplies;
    }
    
    @Override
    public List<ArticleReply> selectByUserId(Long userId, Integer page, Integer size) {
        // 校验参数
        if(userId == null || userId <= 0 || page == null || page < 1 || size == null || size < 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        // 计算偏移量
        int offset = (page - 1) * size;
        
        // 查询用户的评论
        List<ArticleReply> userReplies = articleReplyMapper.selectByUserId(userId, offset, size);
        if(userReplies == null) {
            userReplies = new ArrayList<>();
        }
        
        return userReplies;
    }

    @Override
    public Integer countByUserId(Long userId) {
        // 校验参数
        if(userId == null || userId <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        // 获取用户评论总数
        return articleReplyMapper.countByUserId(userId);
    }
    
    @Override
    public ArticleReply getById(Long id) {
        // 校验参数
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        // 获取评论详情
        return articleReplyMapper.selectByPrimaryKey(id);
    }
    
    @Override
    public void deleteById(Long id) {
        // 校验参数
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        // 获取评论详情
        ArticleReply reply = articleReplyMapper.selectByPrimaryKey(id);
        if (reply == null || reply.getDeleteState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString() + " 评论不存在或已被删除 id=" + id);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE, "评论不存在或已被删除"));
        }
        
        // 逻辑删除评论（将删除状态设置为1）
        ArticleReply updateReply = new ArticleReply();
        updateReply.setId(id);
        updateReply.setDeleteState((byte) 1);
        updateReply.setUpdateTime(new Date());
        
        int rows = articleReplyMapper.updateByPrimaryKeySelective(updateReply);
        if (rows != 1) {
            // 打印日志
            log.error(ResultCode.ERROR_SERVICES.toString() + " 删除评论失败 id=" + id);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        
        // 减少文章的评论计数
        try {
            // 获取文章详情
            Article article = articleMapper.selectByPrimaryKey(reply.getArticleId());
            if (article != null && article.getReplyCount() > 0) {
                // 更新文章评论计数
                Article updateArticle = new Article();
                updateArticle.setId(reply.getArticleId());
                updateArticle.setReplyCount(article.getReplyCount() - 1);
                articleMapper.updateByPrimaryKeySelective(updateArticle);
            }
            
            // 减少用户评论计数
            userService.subOneCommentCountById(reply.getPostUserId());
            
            log.info("评论删除成功: id={}, 文章id={}, 用户id={}", id, reply.getArticleId(), reply.getPostUserId());
        } catch (Exception e) {
            // 记录异常但不阻止删除操作
            log.error("更新文章评论计数或用户评论计数失败", e);
        }
    }

    @Override
    public void adminDeleteComment(Long id) {
        // 校验参数
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        // 获取评论详情
        ArticleReply reply = articleReplyMapper.selectByPrimaryKey(id);
        if (reply == null || reply.getDeleteState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString() + " 评论不存在或已被删除 id=" + id);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE, "评论不存在或已被删除"));
        }
        
        // 调用已有的删除方法
        this.deleteById(id);
        
        // 记录管理员操作日志
        log.info("管理员删除评论: id={}, 文章id={}, 用户id={}", id, reply.getArticleId(), reply.getPostUserId());
    }
    
    @Override
    public void ignoreReports(Long id) {
        // 校验参数
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        // 获取评论详情
        ArticleReply reply = articleReplyMapper.selectByPrimaryKey(id);
        if (reply == null || reply.getDeleteState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString() + " 评论不存在或已被删除 id=" + id);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE, "评论不存在或已被删除"));
        }
        
        // 清除举报标记或更新评论状态为已处理
        // 这里假设数据库中有相关字段或表
        try {
            // 这里需要根据具体的数据库结构实现
            // 例如：commentReportMapper.clearReportsByCommentId(id);
            
            // 更新评论状态
            ArticleReply updateReply = new ArticleReply();
            updateReply.setId(id);
            updateReply.setState((byte) 0); // 假设0是正常状态
            updateReply.setUpdateTime(new Date());
            
            int rows = articleReplyMapper.updateByPrimaryKeySelective(updateReply);
            if (rows != 1) {
                // 打印日志
                log.error(ResultCode.ERROR_SERVICES.toString() + " 忽略评论举报失败 id=" + id);
                // 抛出异常
                throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
            }
            
            log.info("忽略评论举报成功: id={}", id);
        } catch (Exception e) {
            log.error("忽略评论举报出错", e);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }
    
    @Override
    public List<Map<String, Object>> getReportListByCommentId(Long id) {
        // 校验参数
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        // 获取评论详情
        ArticleReply reply = articleReplyMapper.selectByPrimaryKey(id);
        if (reply == null || reply.getDeleteState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString() + " 评论不存在或已被删除 id=" + id);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE, "评论不存在或已被删除"));
        }
        
        // 获取评论的举报列表
        // 这里需要根据具体的数据库结构实现
        try {
            // 实际应该从数据库中查询
            // 例如：return commentReportMapper.selectByCommentId(id);
            
            // 由于没有实际的举报表实现，这里返回空列表
            return new ArrayList<>();
        } catch (Exception e) {
            log.error("获取评论举报列表出错", e);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }
    
    @Override
    public List<Map<String, Object>> getCommentsByPage(int page, int size, String keyword, String status) {
        // 校验参数
        if (page < 1 || size < 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        try {
            // 计算偏移量
            int offset = (page - 1) * size;
            
            // 将状态字符串转换为byte值
            Byte statusValue = null;
            if (status != null && !status.isEmpty()) {
                try {
                    statusValue = Byte.parseByte(status);
                } catch (NumberFormatException e) {
                    log.warn("状态值解析错误: " + status);
                }
            }
            
            // 从数据库获取评论列表
            List<ArticleReply> commentList = articleReplyMapper.selectByPage(offset, size, keyword, statusValue);
            log.info("查询到{}条评论记录", commentList != null ? commentList.size() : 0);
            
            // 组装返回结果，包含更多信息
            List<Map<String, Object>> resultList = new ArrayList<>();
            
            for (ArticleReply comment : commentList) {
                // 获取文章信息，检查文章是否已被删除
                Article article = null;
                try {
                    log.debug("获取评论ID: {} 关联的文章，文章ID: {}", comment.getId(), comment.getArticleId());
                    article = articleService.selectById(comment.getArticleId());
                    // 如果文章不存在或已被删除，跳过此评论
                    if (article == null) {
                        log.info("跳过评论ID: {}，因为关联的文章ID: {} 不存在或已被删除", comment.getId(), comment.getArticleId());
                        continue;
                    }
                } catch (Exception e) {
                    // 如果获取文章发生异常，视为文章已删除，跳过此评论
                    log.warn("获取文章信息失败，文章ID: {}, 评论ID: {}, 错误: {}", 
                            comment.getArticleId(), comment.getId(), e.getMessage());
                    continue;
                }
                
                Map<String, Object> commentMap = new HashMap<>();
                
                // 评论基本信息
                commentMap.put("id", comment.getId());
                commentMap.put("articleId", comment.getArticleId());
                commentMap.put("userId", comment.getPostUserId());
                commentMap.put("content", comment.getContent());
                commentMap.put("createTime", comment.getCreateTime());
                commentMap.put("likeCount", comment.getLikeCount());
                commentMap.put("status", comment.getState());
                
                // 设置文章标题
                commentMap.put("articleTitle", article.getTitle());
                
                // 获取用户信息
                try {
                    Map<String, Object> user = userService.selectUserInfoById(comment.getPostUserId());
                    if (user != null) {
                        commentMap.put("username", user.get("nickname"));
                        commentMap.put("userAvatar", user.get("avatarUrl"));
                    } else {
                        commentMap.put("username", "未知用户");
                        commentMap.put("userAvatar", "");
                    }
                } catch (Exception e) {
                    commentMap.put("username", "未知用户");
                    commentMap.put("userAvatar", "");
                    log.error("获取用户信息出错: " + e.getMessage(), e);
                }
                
                // 添加到结果列表
                resultList.add(commentMap);
            }
            
            log.info("过滤后返回{}条评论记录", resultList.size());
            return resultList;
        } catch (Exception e) {
            log.error("获取评论列表出错", e);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }
    
    @Override
    public int countCommentsByCondition(String keyword, String status) {
        try {
            // 将状态字符串转换为byte值
            Byte statusValue = null;
            if (status != null && !status.isEmpty()) {
                try {
                    statusValue = Byte.parseByte(status);
                } catch (NumberFormatException e) {
                    log.warn("状态值解析错误: " + status);
                }
            }
            
            // 先从数据库获取符合条件的评论数量
            int totalCount = articleReplyMapper.countByCondition(keyword, statusValue);
            log.debug("初步统计符合条件的评论数: {}", totalCount);
            
            // 如果没有符合条件的评论，直接返回0
            if (totalCount == 0) {
                return 0;
            }
            
            // 如果评论数量超过100，为了性能考虑，不进行精确过滤，而是返回粗略估计
            // 这是一个折衷方案，避免在数据量大时导致性能问题
            if (totalCount > 100) {
                log.info("评论数量较大({}条)，返回估计值", totalCount);
                // 可以根据历史数据统计一个大致比例，这里假设90%的评论关联的文章都存在
                return (int)(totalCount * 0.9);
            }
            
            // 获取符合条件的所有评论ID列表，用于筛选关联已删除文章的评论
            List<ArticleReply> allMatchingComments = articleReplyMapper.selectAllByCondition(keyword, statusValue);
            log.debug("获取到符合条件的评论列表，数量: {}", allMatchingComments.size());
            
            // 计算有效评论数量（排除关联到已删除文章的评论）
            int validCount = 0;
            for (ArticleReply comment : allMatchingComments) {
                try {
                    Article article = articleService.selectById(comment.getArticleId());
                    if (article != null) {
                        validCount++;
                    } else {
                        log.debug("评论ID: {} 关联的文章ID: {} 不存在或已被删除，不计入统计", 
                                comment.getId(), comment.getArticleId());
                    }
                } catch (Exception e) {
                    log.warn("获取文章信息失败，文章ID: {}, 评论ID: {}, 错误: {}", 
                            comment.getArticleId(), comment.getId(), e.getMessage());
                    // 出错时视为文章已删除，不计入统计
                }
            }
            
            log.info("过滤后的有效评论数: {}", validCount);
            return validCount;
        } catch (Exception e) {
            log.error("统计评论数量出错", e);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }
}
